import React, { useEffect, useState } from 'react';
import { Button, Form, Input, Space, Modal, Radio } from 'antd';
import { validateFileExist, generateFrontEntity } from '@/services/generatorService'
import CollapsePanel from '@/components/CollapsePanel/index';
import { ExclamationCircleFilled } from '@ant-design/icons';
import type { RadioChangeEvent } from 'antd/es/radio';
import { getGenerateConfigAll, addGenerateConfig, patchGenerateConfig } from '@/services/generateConfigService';

interface Props {
  TableInfo: Generator.TableInfo
}

type FieldType = {
  entityName?: string;
  filePath: string;
};

const FrontEntity: React.FC<Props> = (props) => {
  const typeName = "FrontEntity";
  const { TableInfo } = props;
  const { confirm } = Modal;
  const [value, setValue] = useState<string>('');
  const [form] = Form.useForm();
  const [disabled, setDisabled] = useState<boolean>(false);
  const [radioValue, setRadioValue] = useState<number>(1);

  const generateCode = async (values: any) => {
    let promise = Promise.resolve();
    // 生成代码的时候将配置存储到数据库，下次可以不用再进行填写
    // 先判断有没有 如果没有的话就新增，有的话就修改 -1 后面需要改成登陆人Id
    if (radioValue === 2) {
      promise = getGenerateConfigAll({ "@filter": `eq(Name,${typeName})&eq(AddUserId,${-1})`, "@fields": "Id" }).then(generateConfigResponse => {
        if (generateConfigResponse.Items.length > 0) {
          patchGenerateConfig(generateConfigResponse.Items[0].Id, values.filePath);
        } else {
          addGenerateConfig({ Name: typeName, AddUserId: -1, FilePath: values.filePath });
        }
      })
    }

    promise.then(() => {
      generateFrontEntity({ Name: values.entityName, TableInfo: TableInfo, FilePath: values.filePath, IsFrontCode: true, IsGenerateFile: radioValue === 2, Extension: '.d.ts' }).then(response => {
        const { Items } = response;
        setValue(Items[0]);
      })
    })
  }

  const beforeValidate = async (values: any) => {
    if (radioValue !== 2) {
      generateCode(values);
      return;
    }
    return validateFileExist({ entityName: values.entityName, filePath: values.filePath, extension: '.d.ts' })
      .then((result: boolean) => {
        if (result) {
          confirm({
            title: '确认',
            icon: <ExclamationCircleFilled />,
            content: '文件已经存在，确认覆盖嘛？',
            onOk() {
              generateCode(values);
            },
            onCancel() {
              return;
            },
          });
        } else {
          generateCode(values);
        }
      });
  }

  const onFinish = async (values: any) => {
    beforeValidate(values);
  }

  const getBaseFilePath = (type: string) => {
    getGenerateConfigAll({ "@filter": `eq(Name,${type})&eq(AddUserId,${-1})` }).then(generateConfigResponse => {
      const { Items } = generateConfigResponse;
      form.setFieldValue("filePath", Items[0]?.FilePath);
    });
  }

  useEffect(() => {
    form.validateFields(['filePath'])
    getBaseFilePath(typeName)
  }, [form, disabled])

  const onFinishFailed = async (errorInfo: any) => {
    console.log(errorInfo);
  }

  const radioChange = (e: RadioChangeEvent) => {
    setDisabled(e.target.value === 2);
    setRadioValue(e.target.value);
  };

  return (
    <>
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        layout="vertical"
        onFinish={onFinish}
        form={form}
        onFinishFailed={onFinishFailed}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        autoComplete="off"
      >
        <Form.Item<FieldType>
          label="实体类名称"
          name="entityName"
          rules={[{ required: true, message: '请输入实体类名称!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item<FieldType>
          label="生成路径"
          name="filePath"
          dependencies={['radioType']}
          rules={[{ required: disabled, message: '请输入生成路径!' }]}
        >
          <Input disabled={!disabled} />
        </Form.Item>

        <Form.Item<FieldType>
          label="选项"
        >
          <Radio.Group name='radioType' onChange={radioChange} defaultValue={radioValue} value={radioValue}>
            <Radio value={1}>预览</Radio>
            <Radio value={2}>生成</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item>
          <Space>
            <Button disabled={disabled} type="primary" htmlType="submit">
              预览
            </Button>
            <Button disabled={!disabled} type="default" htmlType="submit" >
              生成
            </Button>
          </Space>
        </Form.Item>
      </Form>

      <CollapsePanel languageType='javascript' value={value} title='前端实体类' setValue={setValue} />
    </>
  )
}

export default FrontEntity;
